package com.jinlejia.bbs.widget.musicView;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import com.jinlejia.bbs.widget.mp3.Mp3View;

/**
 * @author 王进 on 2019/4/9.
 */

public class Mp3Player implements ServiceConnection {
    private volatile Host host;
    private Mp3Player(Host host){
        this.host = host;
    }

    private static Mp3Player player;
    public static Mp3Player get(Context context){
        if (player==null){
            player = new Mp3Player(Host.create(context));
        }
        return player;
    }

    public void init(){
        if (!host.isAlive())return;
        if (mediaService!=null)return;
        Intent intent = new Intent(host.getContext(),MediaPlayerService.class);
        host.getContext().bindService(intent,this,Context.BIND_AUTO_CREATE);
    }

    public void play(final String url){
        if (!host.isAlive()){
            return; //如果Activity已经销毁，则不进行播放
        }
        mediaService.startMediaPlayer(url);
    }

    private void pauseAll(){
    }


    public void release(){
        player = null;
        if (mediaService!=null){
            mediaService.release();
        }
        if (host.getContext()!=null)
            host.getContext().unbindService(this);
    }

    private MediaPlayerService mediaService;
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        MediaPlayerService.MediaBinder binder = (MediaPlayerService.MediaBinder) service;
        mediaService = binder.getService();
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }

    public interface Mp3PlayerListener{
        void onProcess(int current,int duration);
    }

}
